/*
 * File Name：UnitSpeechView.java
 * Copyright：Copyright 2008-2014 CiWong.Inc. All Rights Reserved.
 * Description： UnitSpeechView.java
 * Modify By：jejun
 * Modify Date：2014-1-24
 * Modify Type：Add
 */
package com.ciwong.epaper.modules.evaluate.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.PlaybackParams;
import android.os.Build;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.TextView;

import com.ciwong.ciwongwrite.utils.CWUtils;
import com.ciwong.epaper.R;
import com.ciwong.epaper.application.EApplication;
import com.ciwong.epaper.modules.epaper.bean.Answer;
import com.ciwong.epaper.modules.epaper.bean.IntensiveReadingResultBean;
import com.ciwong.epaper.modules.epaper.bean.WorkAnswers;
import com.ciwong.epaper.modules.evaluate.bean.AnswerRecorder;
import com.ciwong.epaper.modules.evaluate.bean.RepeatAnswerInfo;
import com.ciwong.epaper.modules.evaluate.bean.WordDetail;
import com.ciwong.epaper.modules.evaluate.ui.SentenceRepeatActivity;
import com.ciwong.epaper.modules.evaluate.ui.WordBottomView;
import com.ciwong.epaper.modules.evaluate.ui.WordReadActivity;
import com.ciwong.epaper.modules.me.bean.RequirementContent;
import com.ciwong.epaper.modules.me.ui.JsonParserUtil;
import com.ciwong.epaper.modules.me.util.UploadFileHelper;
import com.ciwong.epaper.util.ALiYunManager;
import com.ciwong.epaper.util.DialogUtil;
import com.ciwong.epaper.util.EConstants;
import com.ciwong.epaper.util.ESystem;
import com.ciwong.epaper.widget.evaluate.UnitSpeechView;
import com.ciwong.libs.audio.play.AudioPlayer;
import com.ciwong.libs.audio.play.OnPlayListener;
import com.ciwong.libs.oralevaluate.bean.EvaluateResult;
import com.ciwong.libs.oralevaluate.bean.Word;
import com.ciwong.libs.utils.CWLog;
import com.ciwong.libs.utils.CWSys;
import com.ciwong.libs.utils.StringUtils;
import com.ciwong.mobilelib.bean.UserInfoBase;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.BaseConstants;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;
import com.unisound.edu.oraleval.sdk.sep15.IOralEvalSDK;
import com.unisound.edu.oraleval.sdk.sep15.SDKError;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * 单元单词语音
 *
 * @author jejun
 * @version ciwong v.1.0 2014-1-24
 * @since ciwong v.1.0
 */
public class UnitSpeechControler extends SpeechController implements
        UnitSpeechView.OnPageSelectChangeListener, OnItemClickListener {

    private WordReadActivity mActivity;
    private UnitSpeechView speechView;

    private List<WordDetail> unitWords;

    private TextView scoreView;
    private TextView see_work_score_text;
    private TextView completion_text;
    private TextView smooth_text;
    private TextView accuracy_text;

    private String unitText;

    private long startTime;

    private ListAdapter adapter;

    private OnSpeechListener mOnUnitSpeechListener;

    private RequirementContent requContent;

    private int readMode;// 单词跟读模式
    //作业开始时间
    private long startWorkTime;

    public boolean isRepeatWord;//是否来自于单词重读
    private final long RECORD_ADD_DURATION = 1000;//录音延长时间
    private Runnable runnableComplateRecord;
    private OnShowFirstRecordTipListener onShowFirstRecordTipListener;
    /**
     * 默认服务包剩余使用时间
     */
    private boolean serviceExpired;

    public interface OnShowFirstRecordTipListener {
        void onShowFirstRecordTip(long addDuration);
    }

    /**
     * 第一次录音 提示信息回调
     *
     * @param onShowFirstRecordTipListener
     */
    public void setOnShowFirstRecordTipListener(OnShowFirstRecordTipListener onShowFirstRecordTipListener) {
        this.onShowFirstRecordTipListener = onShowFirstRecordTipListener;
    }


    public void setRequContent(RequirementContent requContent) {
        this.requContent = requContent;
    }

    private CWDialog getRecordPermissDialog;

    /**
     * 获取Record权限提示框
     */
    private boolean showgetRecordPermissDialog() {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(mContext, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss();
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(mContext);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(mContext.getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss();
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        if (mContext instanceof WordReadActivity) {
                            ((WordReadActivity) mContext).playOrPause(true, false);
                        }


                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用录音，判断权限
     */
    public boolean checkRecordAudioPermiss() {
        if (Build.VERSION.SDK_INT >= 23
                && mContext.getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions((Activity) mContext, //
                    permissionList, //
                    noteMap, //
                    WordReadActivity.CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
                                record();
                            }
                        }
                    });
        } else {
            record();
        }
        return true;
    }

    /**
     * 设置跟读模式
     *
     * @param readMode
     */
    public void setReadMode(int readMode) {
        this.readMode = readMode;
    }


    private OnPlayListener listener = new OnPlayListener() {
        @Override
        public void stop(Object mp3) {
            if (isPause() || operateStatus == OPERATE_STATUS_STOP) {
                return;
            }
            //这个地方要修改  不要按TAG判断   开始录音
            if (ASIDE_AUDIO_TAG.equals(mp3)) {
                //record();
                showgetRecordPermissDialog();
                return;
            } else if (ASIDE_AUDIO_TAG_EVALUATE.equals(mp3)) {
                if (isRepeatWord) {//重读就不再执行
                    return;
                } else {
                    if (!mActivity.mIsUnAutoMode) {
                        playNext();
                    }
                }

            } else {
                if (!mActivity.mIsUnAutoMode) {
                    //原音播放完成之后需要播放提示音
                    startRecordHint(currentListenAndRepeatIndex);
                } else {
                    //手动
                    speechView.playstopState(false);
                    if (null != userAnswerseList) {
                        //有答案播放音频不直接录音
                        if (userAnswerseList.size() <= currentListenAndRepeatIndex || isRepeatWord) {
                            startRecordHint(currentListenAndRepeatIndex);
                        }
                    }
                }

            }

        }

        @Override
        public void onPlayStart(Object mp3) {

        }

        @Override
        public void onReadPlayer(long duration, Object mp3) {
            if (ASIDE_AUDIO_TAG.equals(mp3)) {
                return;
            }
            // 获取播放单词时长
            if (!"pcm".equals(mp3 + "")) {
                CWLog.e(TAG, "播放语音时间：" + duration + "," + mp3);
                //显示播放单词原音状态
                speechView.play(mActivity.mIsUnAutoMode);//在这里显示是为了错误的时候 还没有显示播放图标
                if (duration < 1000) {
                    duration += 800;
                } else if (duration < 2000) {
                    duration += 500;
                }
                audioDuration = duration + RECORD_ADD_DURATION;
            }
            mActivity.audioDuration = audioDuration;
        }

        @Override
        public void onError(int errorCode, final Object tag) {
            CWLog.e(TAG, "播放语音失败：" + errorCode + "," + tag);

            if (!"pcm".equals(tag + "")) {
                if (eEngine != null) {
                    eEngine.cancel();
                }
                if (!ASIDE_AUDIO_TAG.equals(tag)) {
//                    ToastUtil.INSTANCE.toastCenter(mContext, "播放音频失败", R.mipmap.ic_error);
                    speechView.playHintState(mActivity.mIsUnAutoMode);
                }
                AudioPlayer.getInstance().stop();
            }
            stop(tag);
        }

        @Override
        public void onBuffer(Object mp3, long progress, long total) {

        }

        @Override
        public void onPlaying(long arg0, long arg1) {
            int progress = (int) arg1;
            int max = (int) arg0;
            if (!mActivity.mIsUnAutoMode) {
                mOnUnitSpeechListener.updateProgress(max, progress);//更新播放进度
            }
        }

    };

    /**
     * 构造函数
     *
     * @param mContext 上下文
     */
    protected UnitSpeechControler(BaseActivity mContext) {
        super(mContext);
    }

    /**
     * 构造函数
     *
     * @param unitSpeechView {@link UnitSpeechView}
     */
    public UnitSpeechControler(BaseActivity activity, UnitSpeechView unitSpeechView, long startTime, boolean isExpired) {
        super(activity);
        try {
            mActivity = (WordReadActivity) activity;
            speechView = unitSpeechView;
            startWorkTime = startTime;
            serviceExpired = isExpired;
            init();
        } catch (Exception e) {
            e.getStackTrace();
        }


    }

    private void init() {
        mContext = mActivity;
        speechView.setOnPageSelectChangeListener(this);
        initYZSEngine();
        //上传监听
    }

    /**
     * 设置语音评测监听事件
     *
     * @param listener {@link OnSpeechListener}
     */
    public void setOnUnitSpeechListener(OnSpeechListener listener) {
        this.mOnUnitSpeechListener = listener;
    }

    private File getSoundPath(WordDetail word, int index) {
        return new File(ESystem.getAnswersUserIdMediaPathWord(uuid),
                uuid + StringUtils.md5(word.getWords()) + "&" + startWorkTime
                        + EConstants.AUDIO_DEFAULT_SUFFIX);
    }

    private File getSoundOpusPath(WordDetail word, int index) {
        return new File(ESystem.getAnswersUserIdMediaOpusPathWord(uuid),
                uuid + StringUtils.md5(word.getWords()));
    }

    /**
     * 设置单元单词
     *
     * @param words List<UnitWord>
     */
    public void setUnitWord(List<WordDetail> words, WordBottomView wordBottomView,
                            TextView scoreView, TextView see_work_score_text, TextView completion_text, TextView smooth_text, TextView accuracy_text, String saveUuid, long userId, boolean isRepeatWord) {
        this.isRepeatWord = isRepeatWord;
        unitWords = words;
        this.scoreView = scoreView;
        this.completion_text = completion_text;
        this.see_work_score_text = see_work_score_text;
        this.smooth_text = smooth_text;
        this.accuracy_text = accuracy_text;
        if (!TextUtils.isEmpty(saveUuid)) {
            uuid = saveUuid;
        }
        answerCount = words == null ? 0 : words.size();
        if (speechView != null) {
            speechView.setData(words, wordBottomView, scoreView, userId,
                    currentListenAndRepeatIndex);
        }
        if (unitWords == null || unitWords.isEmpty()) {
            return;
        }
        if (unitText == null || "".equals(unitText)) {
            unitText = StringUtils.md5(words.get(0).getWords() + "");
        }
        int len = words.size();
        for (int i = len - 1; i >= 0; i--) {
            WordDetail word = words.get(i);
            String url = word.getWordFile();
            // if (url != null && !url.startsWith("http://"))
            // {
            // url = TEMP_HTTP + url;
            // }
            word.setWordFile(url);
        }
    }

    /**
     * 设置单元单词标题
     */
    public void setUnitText(String text) {
        unitText = text;
    }

    /**
     * 开始录音提示音
     *
     * @param index 下标
     */
    private void startRecordHint(final int index) {
        if (index >= unitWords.size()) {
            return;
        }
        if (isPause() || operateStatus == OPERATE_STATUS_STOP) {
            return;
        }
        //延时操作   防止跳读
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                AudioPlayer.getInstance().setOnPlayListener(listener).play(R.raw.repeat_read_start_record, mContext,
                        ASIDE_AUDIO_TAG);
            }
        }, 300);
        if (mActivity.mIsUnAutoMode) {
            //手动
            speechView.playstopState(false);
        } else {
            speechView.playHintState(mActivity.mIsUnAutoMode);
        }
    }

    /**
     * 录音
     */
    private void record() {
        if (onShowFirstRecordTipListener != null)//第一次录音 提示信息回调
            onShowFirstRecordTipListener.onShowFirstRecordTip(RECORD_ADD_DURATION);

        if (isPause() || operateStatus == OPERATE_STATUS_STOP) {
            return;
        }
        try {

            //显示录音图标//开始录音动画
            speechView.startRecord(mActivity.mIsUnAutoMode);
            //自动更新进度
            speechView.autoUpdateProgress((int) audioDuration);
            //正常的录音状态，即第一次的录音
            operateStatus = OPERATE_STATUS_RECORDING;
            WordDetail word = unitWords.get(currentListenAndRepeatIndex);
            //启动 增加判断不为"-"
            if (!"".equals(word.getSyllable().trim()) && !"-".equals(word.getSyllable().trim())) {
                eEngine.setText(word.getSyllable());
            } else {
                eEngine.setText(word.getWords());
            }
            //音频文件地址
            eEngine.setRecordPath(getSoundPath(word, currentListenAndRepeatIndex).getAbsolutePath());
            //音频Opus文件地址
            eEngine.SetOpusPath(getSoundOpusPath(word, currentListenAndRepeatIndex).getAbsolutePath());
            UserInfoBase userInfoBase = EApplication.getInstance().getUserInfoBase();
            if (null != userInfoBase) {
                eEngine.setUid(String.valueOf(userInfoBase.getUserId()));
            }

            eEngine.start("E");
            runnableComplateRecord = new Runnable() {
                @Override
                public void run() {
                    complateRecord();
                }
            };
            mHandler.postDelayed(runnableComplateRecord, audioDuration);


        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (OutOfMemoryError error) {
            error.printStackTrace();
        }

    }

    /**
     * 完成录音
     */
    public void complateRecord() {
        mHandler.removeCallbacks(runnableComplateRecord);
        if (isPause()) {
            eEngine.stop();
            return;
        }
        stopRecord();
    }


    /**
     * 停止录音
     */
    private void stopRecord() {
        CWLog.i(TAG, "audioDuration:" + audioDuration);
        if (!(eEngine.getiOralEvalSDKStatus() == 4 || eEngine.getiOralEvalSDKStatus() == 5)) {
            mActivity.showCricleProgress(" 评分中...");
        }
        eEngine.stop();
        //如果是已经暂停了 则不再执行
        if (operateStatus == OPERATE_STATUS_STOP || operateStatus == -OPERATE_STATUS_STOP) {
            return;
        }
        speechView.playHintState(mActivity.mIsUnAutoMode);
    }


    /**
     * 开始学习
     *
     * @param isPlayWord 是否播放音频
     * @param isRecord   是否直接录音
     */
    public void startStudy(boolean isPlayWord, boolean isRecord) {
        try {
            //答案记录
            if (answerRecorders == null) {
                answerRecorders = new ArrayList<AnswerRecorder>();
            }
            operateStatus = OPERATE_STATUS_PLAYING;
            if (isPause() || operateStatus == OPERATE_STATUS_STOP) {
                return;
            }
            //切换单词显示页面
            speechView.animTo(currentListenAndRepeatIndex);
            cacheListenAndRepeatIndex = currentListenAndRepeatIndex;
            if (currentListenAndRepeatIndex >= unitWords.size()) {//暂停时候  最后一题的时候完成试卷
                //已经完成作业
                allComplete(true);
                return;
            }
            //先添加纪录
            if (answerRecorders.size() <= currentListenAndRepeatIndex) {
                AnswerRecorder ar = new AnswerRecorder();
                ar.setwId(unitWords.get(currentListenAndRepeatIndex).getwId());
                StringBuffer sb = new StringBuffer(ALiYunManager.ACCESS_URL);
                sb.append("work/followread/" + CWUtils.getReadTime(startWorkTime) + "/" + CWSys
                        .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/");
                sb.append(uuid + StringUtils.md5(unitWords.get(currentListenAndRepeatIndex).getWords()) + "&" + startWorkTime);
                sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);

                ar.setAliyunSoundUrl(sb.toString());//
                answerRecorders.add(ar);
            }
            startTime = System.currentTimeMillis();
            //设置分数和题号
            onCompleteCount();

            if (readMode == SpeechUtils.WordReadMode.READ_REPEAT) {
                //跟读
                if (isPlayWord) {
                    playWords();
                } else {
                    operateStatus = OPERATE_STATUS_NORMAL;
                    if (isRecord) {
                        //直接录音
                        startRecordHint(currentListenAndRepeatIndex);
                    }
                }
            } else {
                if (isPlayWord || isRecord) {
                    //通读
                    startRecordHint(currentListenAndRepeatIndex);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }
    }

    //播放单词原音
    public void playWords() {
        synchronized (unitWords)//播放原音
        {
            operateStatus = OPERATE_STATUS_PLAYING;
            playStatus = PLAY_STATUS_PLYAING_1;
            if (currentListenAndRepeatIndex >= unitWords.size()) {
                return;
            }
            final WordDetail unitWord = unitWords.get(currentListenAndRepeatIndex);

            String url = ESystem.formatPath(unitWord.getWordFile());
            CWLog.d(TAG, "url:" + url);
            if (TextUtils.isEmpty(url)) {
                int errorResId = R.string.speech_word_url_invalid_1;
                showMsg(errorResId);
                if (isRepeatWord) {//重读
                    mOnUnitSpeechListener.repeatReadFinsh(null, null, null);
                    return;
                } else {
                    playNext();
                }
            } else {
                AudioPlayer.getInstance().setOnPlayListener(listener).play(url,
                        true);
                try {
                    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M && EApplication.getInstance().mPlayerspeed != 1.0f) {
                        MediaPlayer mMediaPlayer = AudioPlayer.getInstance().getMediaPlayer();
                        if (mMediaPlayer != null) {
                            try {
                                PlaybackParams params = mMediaPlayer.getPlaybackParams().setSpeed(EApplication.getInstance().mPlayerspeed);
                                if (params != null) {
                                    mMediaPlayer.setPlaybackParams(params);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public void playNext() {
        long delaytime;
        if (mActivity.mIsUnAutoMode) {
            delaytime = 0;
        } else {
            delaytime = 1400;
        }
        //延迟一秒给用户一秒的时间
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (currentListenAndRepeatIndex < (unitWords.size())) {
                    //设置显示题号
                    onCompleteCount();
                    /*//如果当前播放的下标还在句子列表中就继续播放下一个句子
                    currentListenAndRepeatIndex++;*/
                    scoreView.setVisibility(View.GONE);
                    see_work_score_text.setVisibility(View.GONE);
                    completion_text.setVisibility(View.GONE);
                    smooth_text.setVisibility(View.GONE);
                    accuracy_text.setVisibility(View.GONE);
                    //切换单词显示页面
                    speechView.animTo(currentListenAndRepeatIndex);
                    //cacheListenAndRepeatIndex = currentListenAndRepeatIndex;//修改于显示分数后要播下一题
                    if (answerRecorders.size() <= currentListenAndRepeatIndex) {
                        AnswerRecorder ar = new AnswerRecorder();
                        ar.setwId(unitWords.get(currentListenAndRepeatIndex).getwId());

                        StringBuffer sb = new StringBuffer(ALiYunManager.ACCESS_URL);
                        sb.append("work/followread/" + CWUtils.getReadTime(startWorkTime) + "/" + CWSys
                                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/");
                        sb.append(uuid + StringUtils.md5(unitWords.get(currentListenAndRepeatIndex).getWords()) + "&" + startWorkTime);
                        sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);

                        ar.setAliyunSoundUrl(sb.toString());//
                        answerRecorders.add(ar);
                    } else {
                        if (currentListenAndRepeatIndex >= 0) {
                            if (!mActivity.mIsKaoShiMode) {
                                AnswerRecorder ar = answerRecorders.get(currentListenAndRepeatIndex);
                                if (ar.getSoundUrl() != null && ar.getScore() != -1) {
                                    showResultScore(serviceExpired, ar.getScore(), ar.getIntegrity(), ar.getFluency(), ar.getPronunciation());
                                }
                            }
                        }
                    }
                    startTime = System.currentTimeMillis();
                    if (readMode == SpeechUtils.WordReadMode.READ_REPEAT) {//跟读
                        if (!mActivity.mIsUnAutoMode) {
                            playWords();
                        } else {
                            //是否是返回上一个
                            boolean isBack = false;
                            EvaluateResult evaluateResult = null;
                            if (userAnswerseList != null && userAnswerseList.size() > 0
                                    && currentListenAndRepeatIndex >= 0 && currentListenAndRepeatIndex < userAnswerseList.size()) {
                                WorkAnswers<RepeatAnswerInfo> answers = userAnswerseList.get(currentListenAndRepeatIndex);
                                isBack = true;
                                if (serviceExpired && answers != null && answers.getAnswers() != null && answers.getAnswers().size() > 0) {
                                    RepeatAnswerInfo repeatAnswerInfo = answers.getAnswers().get(0);
                                    if (repeatAnswerInfo != null && EApplication.isSymbolColoration) {
                                        evaluateResult = JsonParserUtil.fromJson(repeatAnswerInfo.getLines(), EvaluateResult.class);
                                        speechView.showResult(evaluateResult);
                                        //音标染色
                                        if (EApplication.isSymbolColoration) {
                                            speechView.setSymbolColoration(evaluateResult);
                                        }
                                    }
                                }
                            }
                            if (currentListenAndRepeatIndex >= 0 && answerRecorders.size() > currentListenAndRepeatIndex) {
                                AnswerRecorder ar = answerRecorders.get(currentListenAndRepeatIndex);
                                mActivity.setResultScoreStatus(ar);
                            }
                            if (!isBack) {
                                //手动模式只有点下一个才自动播放原音
                                playWords();
                            } else {
                                if (mContext instanceof WordReadActivity) {
                                    ((WordReadActivity) mContext).playOrPause(true, false);
                                }
                                //cancelEngine();
                            }

                        }
                    } else {
                        if (!mActivity.mIsUnAutoMode) {
                            //通读
                            startRecordHint(currentListenAndRepeatIndex);
                        } else {
                            EvaluateResult evaluateResult = null;
                            if (userAnswerseList != null && userAnswerseList.size() > 0
                                    && currentListenAndRepeatIndex >= 0 && currentListenAndRepeatIndex < userAnswerseList.size()) {
                                WorkAnswers<RepeatAnswerInfo> answers = userAnswerseList.get(currentListenAndRepeatIndex);
                                if (serviceExpired && answers != null && answers.getAnswers() != null && answers.getAnswers().size() > 0) {
                                    RepeatAnswerInfo repeatAnswerInfo = answers.getAnswers().get(0);
                                    if (repeatAnswerInfo != null && EApplication.isSymbolColoration) {
                                        evaluateResult = JsonParserUtil.fromJson(repeatAnswerInfo.getLines(), EvaluateResult.class);
                                        speechView.showResult(evaluateResult);
                                        //音标染色
                                        if (EApplication.isSymbolColoration) {
                                            speechView.setSymbolColoration(evaluateResult);
                                        }
                                    }
                                }
                            }
                            if (currentListenAndRepeatIndex >= 0) {
                                AnswerRecorder ar = answerRecorders.get(currentListenAndRepeatIndex);
                                mActivity.setResultScoreStatus(ar);
                            }
                        }
                    }
                    //刷新UI

                } else {
                    allComplete(true);
                }


            }
        }, delaytime);
    }


    /**
     * 已跟读完所有，刷新UI
     */
    public void allComplete(boolean isPlayAudio) {
        Answer answer = new Answer();
        answer.setWorkLong(totalTime / 1000);
        // 此时调用此接口方法，意图为通知UI，跟读全部完成，弹出交作业进度条
        mOnUnitSpeechListener.onAllComplete(answer,
                userAnswerseList, answerRecorders, uuid, getAvgScore());

    }

    private void onOneWordComplete(int index, final EvaluateResult evaluateResult, final String yzsAudioUrl) {

        try {
            if (index < answerRecorders.size()) {
                final AnswerRecorder ar = answerRecorders.get(index);
                long time = (System.currentTimeMillis() - startTime);
                CWLog.i("debug", "onOneWordComplete transcoding:" + ar.getSoundUrl()
                        + "     time:" + time);
                ar.setUsetime(time);

                if (isRepeatWord) {
                    //来自重读逻辑
                    upSoundToaliyun(ar);
                    if (isPlayAssess) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mOnUnitSpeechListener.repeatReadFinsh(ar, evaluateResult, yzsAudioUrl);
                            }
                        }, 4000);
                    } else {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                mOnUnitSpeechListener.repeatReadFinsh(ar, evaluateResult, yzsAudioUrl);
                            }
                        }, 500);
                    }
                    return;
                } else {
                    //实时上传音频文件
                    upSoundToaliyun(ar);
                    addAnswer(ar, index, evaluateResult, yzsAudioUrl);
                }
            }
        } catch (Exception e) {
            e.getStackTrace();
        }

    }

    //上传音频到阿里云
    public void upSoundToaliyun(AnswerRecorder ar) {
        if (ar.getSoundUrl() == null) {
            return;
        }

        if (EConstants.IS_YOUKE) {
            //do nothing
        } else {
            ALiYunManager.getInstance().addMP3(ar.getSoundUrl(),
                    ar.getSoundUrl(), startWorkTime);
        }

    }

    /**
     * 添加答案
     *
     * @param ar
     */
    private void addAnswer(AnswerRecorder ar, int index, EvaluateResult evaluateResult, String yzsAudioUrl) {
        String versionId = unitWords.get(index).getwId();
        WorkAnswers tempWorkAnswers = new WorkAnswers();
        tempWorkAnswers.setVersionId(versionId);
        int answerIndex = userAnswerseList.indexOf(tempWorkAnswers);
        if (answerIndex != -1) // 该对象已经存在
        {
            userAnswerseList.remove(answerIndex);
        }
        WorkAnswers workAnswers = new WorkAnswers();
        workAnswers.setVersionId(versionId);
        workAnswers.setScore(ar.getScore());
        workAnswers.setAssess(WorkAnswers.Assess.ASSESS_UNKNOWN);
        List<RepeatAnswerInfo> details = new ArrayList<RepeatAnswerInfo>();
        RepeatAnswerInfo entity = new RepeatAnswerInfo();
        // String[] arr = unitWords.get(index).getWordDetails().split(" ");
        entity.setWord(unitWords.get(index).getWords());
        String soundUrl = ar.getSoundUrl();


        StringBuffer sb = new StringBuffer(ALiYunManager.ACCESS_URL);
        sb.append("work/followread/" + CWUtils.getReadTime(startWorkTime) + "/" + CWSys
                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/");
        sb.append(uuid + StringUtils.md5(unitWords.get(index).getWords()) + "&" + startWorkTime);
        sb.append(EConstants.AUDIO_DEFAULT_SUFFIX);
        entity.setAudioUrl(sb.toString());
        entity.setYzsAudioUrl(yzsAudioUrl);
        entity.setFluency(evaluateResult.getFluency());
        entity.setIntegrity(evaluateResult.getIntegrity());
        entity.setPronunciation(evaluateResult.getPronunciation());


        entity.setReadTimes(
                requContent == null ? 1 : requContent.getReadtimes());
        entity.setAudioDuration(audioDuration);

        if (EApplication.isSymbolColoration) {
            String evaluateResultString = JsonParserUtil.toJson(evaluateResult);
            if (!TextUtils.isEmpty(evaluateResultString)) {
                entity.setLines(evaluateResultString);
            }
        }


        totalTime += (int) ar.getUsetime();
        details.add(entity);
        workAnswers.setAnswers(details);
        userAnswerseList.add(workAnswers);

        Log.d(TAG, "########addAnswer mOnUnitSpeechListener.onSaveRecord###########" + uuid);

        mOnUnitSpeechListener.onSaveRecord(userAnswerseList, answerRecorders, uuid);
    }

    private void onCompleteCount() {
        if (mOnUnitSpeechListener != null) {
            mHandler.post(new Runnable() {
                @Override
                public void run() {
                    mOnUnitSpeechListener.onComplete();
                }
            });
        }
    }


    /**
     * 暂停
     */
    public void pause() {
        if (operateStatus < 0) {
            return;
        }
        operateStatus = -operateStatus;
        if (operateStatus == OPERATE_STATUS_PLAY_PAUSE
                || operateStatus == OPERATE_STATUS_COMPARISON_PAUSE) {
            AudioPlayer.getInstance().stop();
        } else if (operateStatus == OPERATE_STATUS_RECORD_PAUSE) {
            eEngine.cancel();
        }
        speechView.setCanScroll(false);//设置是否可以滑动  不可以滑动
        speechView.resetInitState(mActivity.mIsUnAutoMode);
    }

    /**
     * 停止跟读
     */
    public void stop() {
        ////停止状态
        operateStatus = OPERATE_STATUS_STOP;
        AudioPlayer.getInstance().stop();
        speechView.resetInitState(mActivity.mIsUnAutoMode);
        if (eEngine != null) {
            eEngine.stop();
        }
        mHandler.removeCallbacksAndMessages(this);
    }

    /**
     * 终止录音
     */
    public void cancelEngine() {
        if (eEngine != null) {
            eEngine.cancel();
        }
    }

    /**
     * 释放资源
     */
    public void release() {
//         if (eEngine != null)
//         {
//             eEngine.release();
//         }
    }

    @Override
    public void onError(IOralEvalSDK iOralEvalSDK, SDKError sdkError, IOralEvalSDK.OfflineSDKError offlineSDKError) {
        SDKError.Category category = sdkError.category;
        mActivity.hideCricleProgress();
        if (SDKError.Category.Device == category) {
            operateStatus = OPERATE_STATUS_RECORD_PAUSE;
            //录音按钮重置到初始状态
            speechView.resetInitState(mActivity.mIsUnAutoMode);
            //DialogUtil.showSettingPermissions(mContext);
        } else {
            onEvaluated(-1, 0, 0, 0, isPlayAssess);
            EvaluateResult eResult = new EvaluateResult();
            onOneWordComplete(currentListenAndRepeatIndex, eResult, "");
            if (!mActivity.mIsUnAutoMode) {
                currentListenAndRepeatIndex++;
                cacheListenAndRepeatIndex = currentListenAndRepeatIndex;
            }
            if (!isPlayAssess) {
                if (isRepeatWord) {//重读就不再执行
                    operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                    return;
                } else {
                    if (operateStatus != OPERATE_STATUS_PLAY_PAUSE) {
                        if (!mActivity.mIsUnAutoMode) {
                            playNext();
                        } else {
                            operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                        }
                    } else {
                        operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                    }
                }
            } else {
                operateStatus = OPERATE_STATUS_RECORD_PAUSE;
            }
        }
        if (mOnUnitSpeechListener != null) {
            mOnUnitSpeechListener.recError(iOralEvalSDK, sdkError, offlineSDKError);
        }
    }

    @Override
    public void onStart() {
        // BaseApplication.log = YZSEngine.sb;
    }

    private boolean isSoundToLow = true;

    @Override
    public void onVolume(int rms) {
        speechView.setRms(rms);
        if (rms > 40) {
            isSoundToLow = false;
        }
    }

    @Override
    public void onStop(final int i, final EvaluateResult eResult, final String url) {
        mActivity.hideCricleProgress();
        if (i == -3) {//没有权限的时候  应该暂停
            //speechView.resetInitState();//如果暂停  则要暂停按钮状态改变
            pause();//暂停状态
            return;
        }
        //无评测结果
        if (eResult == null) {
            onError(null, new SDKError(SDKError.Category.Server, -9999, null), null);
            return;
        }
        eResult.setScore(SpeechUtils
                .scoreOptimize(eResult.getScore()));

        mHandler.post(new Runnable() {
            @Override
            public void run() {
                if (i == -2) {// 评测库返回错误
                    speechView.playHintState(mActivity.mIsUnAutoMode);
                }
                int score = (int) eResult.getScore();
                onEvaluated(score, eResult.getIntegrity(), eResult.getFluency(), eResult.getPronunciation(), isPlayAssess);
                if (serviceExpired) {
                    speechView.showResult(eResult);
                    //音标染色
                    if (EApplication.isSymbolColoration) {
                        speechView.setSymbolColoration(eResult);
                    }
                }

                //添加答案并保存答案
                onOneWordComplete(currentListenAndRepeatIndex, eResult, url);
                //如果当前播放的下标还在句子列表中就继续播放下一个句子

                if (mActivity.mIsUnAutoMode) {//精读模式下  UI展示
                    mActivity.setResultScoreStatus(answerRecorders.get(currentListenAndRepeatIndex));
                }
                showResultScore(serviceExpired, eResult.getScore(), eResult.getIntegrity(), eResult.getFluency(), eResult.getPronunciation());//显示分数

                if ((readCount <= 3 && score < 80 && isSoundToLow)) {
                    ToastUtil.INSTANCE.toastCenter(mContext, R.string.read_sound_too_low_tips, R.mipmap.ic_increase_volume);
                }

                Log.e(TAG, "score retryscore2: " + currentListenAndRepeatIndex);

                isSoundToLow = true;
                if (!mActivity.mIsUnAutoMode) {
                    currentListenAndRepeatIndex++;
                    cacheListenAndRepeatIndex = currentListenAndRepeatIndex;
                }

                if (!isPlayAssess) {
                    if (isRepeatWord) {//重读就不再执行
                        operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                        return;
                    } else {
                        if (operateStatus != OPERATE_STATUS_PLAY_PAUSE) {
                            if (!mActivity.mIsUnAutoMode) {
                                playNext();
                            } else {
                                operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                            }
                        } else {
                            operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                        }
                    }
                } else {
                    operateStatus = OPERATE_STATUS_RECORD_PAUSE;
                }
            }
        });
        // BaseApplication.log = YZSEngine.sb;
    }

    private IntensiveReadingResultBean getIntensiveReadingResultBean(EvaluateResult evaluateResult) {
        IntensiveReadingResultBean intensiveReadingResultBean = new IntensiveReadingResultBean();
        AnswerRecorder answerRecorder = answerRecorders.get(currentListenAndRepeatIndex);
        if (answerRecorder != null) {
            intensiveReadingResultBean.setLocalAudioUrl(answerRecorder.getSoundUrl());
        }
        intensiveReadingResultBean.setEvaluateResult(evaluateResult);
        if (speechView != null) {
            intensiveReadingResultBean.setOriginalSentence(speechView.getSentence());
        }
        return intensiveReadingResultBean;
    }

    public static int readCount = 0;

    //录音结束后回调
    @Override
    public void onStartOralEval() {
        readCount++;
    }

    private AnswerRecorder onEvaluated(int score, float integrity, float fluency, float pronunciation, boolean playResult) {
        if (currentListenAndRepeatIndex >= unitWords.size()) {
            return null;
        }
        WordDetail word = unitWords.get(currentListenAndRepeatIndex);
        return onEvaluated(score, integrity, fluency, pronunciation, getSoundPath(word, currentListenAndRepeatIndex).getAbsolutePath(),
                playResult);
    }

    @Override
    public void randomShow() {
        WordDetail word = unitWords.get(currentListenAndRepeatIndex);
        String[] arr = SpeechUtils.replaceAsSpace(word.getWords()).split("");
        List<Word> gradeWords = new ArrayList<Word>();
        for (String s : arr) {
            Word w = new Word();
            w.setText(s);
//            int random = (int) (Math.random() * 10 / 2);
            w.setScore(0);
            gradeWords.add(w);
        }
//        final float score = (int) (Math.random() * 10 / 2);
        EvaluateResult eResult = new EvaluateResult();
        eResult.setScore(0);
        eResult.setWords(gradeWords);
        AnswerRecorder ar = onEvaluated(0, 0, 0, 0, true);
        if (ar != null) {
            eResult.setScore(ar.getScore());
        }
        speechView.showResult(eResult);
    }

    @Override
    public void onPageSelected(int index) {
        currentListenAndRepeatIndex = index;
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
                            long id) {

    }

    //隐藏评测结果
    public void hintResultScore() {
        scoreView.setVisibility(View.GONE);
        see_work_score_text.setVisibility(View.GONE);
        completion_text.setVisibility(View.GONE);
        smooth_text.setVisibility(View.GONE);
        accuracy_text.setVisibility(View.GONE);
    }

    /**
     * @param isExpired     默认服务包是否有效
     * @param score         分数
     * @param integrity     完整度l
     * @param fluency       流利度
     * @param pronunciation 准确度
     */
    public void showResultScore(boolean isExpired, float score, float integrity, float fluency, float pronunciation) {
        if (!isExpired) {
            if (null != scoreView) {
                scoreView.setText("已提交");
                scoreView.setTextColor(mContext.getResources().getColor(R.color.color_light_green));
                scoreView.setTextSize(18);
                scoreView.setVisibility(View.VISIBLE);
            }
            if (null != see_work_score_text) {
                see_work_score_text.setVisibility(View.VISIBLE);
            }
            if (null != completion_text) {
                completion_text.setVisibility(View.GONE);
            }
            if (null != smooth_text) {
                smooth_text.setVisibility(View.GONE);
            }
            if (null != accuracy_text) {
                accuracy_text.setVisibility(View.GONE);
            }
            if (!mActivity.mIsUnAutoMode) {
                mHandler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        if (null != scoreView) {
                            scoreView.setVisibility(View.GONE);
                        }
                        if (null != see_work_score_text) {
                            see_work_score_text.setVisibility(View.GONE);
                        }
                    }
                }, 2000);
            }
        } else {
            int bg;
            int scoreColor;
            try {
                if (score < SpeechUtils.SCORE_2) {
                    scoreColor = R.color.score_red;
                    bg = R.mipmap.score_red_rep;
                } else if (score < SpeechUtils.SCORE_4) {
                    scoreColor = R.color.score_yellow;
                    bg = R.mipmap.score_orange_rep;
                } else {
                    scoreColor = R.color.score_green_word;
                    bg = R.mipmap.score_green_rep;
                }
                if (scoreView != null) {
                    Drawable drawable = mContext.getResources().getDrawable(bg);
                    drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
                    scoreView.setCompoundDrawables(null, null, null, drawable);
                    // scoreView.setBackgroundResource(bg);
                    int changeSocre = (int) score;
                    scoreView.setText(changeSocre + "分");
                    scoreView.setTextColor(mContext.getResources().getColor(scoreColor));
                    scoreView.setVisibility(View.VISIBLE);
                    if (!mActivity.mIsUnAutoMode) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (scoreView != null) {
                                    scoreView.setVisibility(View.GONE);
                                }
                            }
                        }, 2000);
                    }
                }
                if (null != see_work_score_text) {
                    see_work_score_text.setVisibility(View.GONE);
                }
                //设置跟读完整度 流畅度 准确度
                if (null != completion_text && null != smooth_text && null != accuracy_text) {
                    int changeIntegrity = (int) integrity;
                    int changeFluency = (int) fluency;
                    int changePronunciation = (int) pronunciation;

                    int integrityColor;
                    int fluencyColor;
                    int pronunciationColor;
                    if (changeIntegrity < SpeechUtils.TOTAL_SCORE_1) {
                        integrityColor = R.color.score_red;
                    } else if (changeIntegrity < SpeechUtils.TOTAL_SCORE_3) {
                        integrityColor = R.color.score_yellow;
                    } else {
                        integrityColor = R.color.score_green_word;
                    }

                    if (changeFluency < SpeechUtils.TOTAL_SCORE_1) {
                        fluencyColor = R.color.score_red;
                    } else if (changeFluency < SpeechUtils.TOTAL_SCORE_3) {
                        fluencyColor = R.color.score_yellow;
                    } else {
                        fluencyColor = R.color.score_green_word;
                    }

                    if (changePronunciation < SpeechUtils.TOTAL_SCORE_1) {
                        pronunciationColor = R.color.score_red;
                    } else if (changePronunciation < SpeechUtils.TOTAL_SCORE_3) {
                        pronunciationColor = R.color.score_yellow;
                    } else {
                        pronunciationColor = R.color.score_green_word;
                    }
                    SpannableString completionText = new SpannableString(mActivity.getString(R.string.completionText, changeIntegrity + ""));
                    SpannableString smoothText = new SpannableString(mActivity.getString(R.string.smoothText, changeFluency + ""));
                    SpannableString accuracyText = new SpannableString(mActivity.getString(R.string.accuracyText, changePronunciation + ""));
                    ForegroundColorSpan colorintegrity = new ForegroundColorSpan(mActivity.getResources().getColor(integrityColor));
                    ForegroundColorSpan colorfluency = new ForegroundColorSpan(mActivity.getResources().getColor(fluencyColor));
                    ForegroundColorSpan colorpronunciation = new ForegroundColorSpan(mActivity.getResources().getColor(pronunciationColor));
                    completionText.setSpan(colorintegrity, 4, mActivity.getString(R.string.completionText, changeIntegrity + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    smoothText.setSpan(colorfluency, 4, mActivity.getString(R.string.smoothText, changeFluency + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    accuracyText.setSpan(colorpronunciation, 4, mActivity.getString(R.string.accuracyText, changePronunciation + "").length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
                    completion_text.setText(completionText);
                    smooth_text.setText(smoothText);
                    accuracy_text.setText(accuracyText);
                    see_work_score_text.setVisibility(View.GONE);
                    completion_text.setVisibility(View.VISIBLE);
                    smooth_text.setVisibility(View.VISIBLE);
                    accuracy_text.setVisibility(View.VISIBLE);
                    if (!mActivity.mIsUnAutoMode) {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                if (completion_text != null) {
                                    completion_text.setVisibility(View.GONE);
                                }
                                if (smooth_text != null) {
                                    smooth_text.setVisibility(View.GONE);
                                }
                                if (accuracy_text != null) {
                                    accuracy_text.setVisibility(View.GONE);
                                }
                            }
                        }, 2000);
                    }
                }
            } catch (Exception e) {
                e.getStackTrace();
            }
        }
    }

    /**
     * 获取上传MP3 文件KEY
     *
     * @param uploadFilePath 上传文件路径
     * @return KEY
     */
    private String getMP3Key(String uploadFilePath) {
        return "work/followread/" + CWUtils.getReadTime(startWorkTime) + "/" + CWSys
                .getSharedLong(BaseConstants.SHARE_PRE_CURR_LOGIN_USER, 0) + "/"
                + new File(uploadFilePath).getName();
    }


}
